package com.se7en.ufutil;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;

public class DiningDisplay extends Activity implements OnClickListener {

	TextView DHName, menu, menuTitle;
	Button update, yest, tomm;
	private static SQLiteDatabase database;
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onPause() {
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dining);
        Bundle extras = getIntent().getExtras();
        
        DHName = (TextView) findViewById(R.id.DHName);
        DHName.setText(extras.getString("name"));
        menu = (TextView) findViewById(R.id.menuText);
        menu.setMovementMethod(new ScrollingMovementMethod()); //This makes it so it can scroll
        menuTitle = (TextView) findViewById(R.id.textDayMenu);
        yest = (Button) findViewById(R.id.yesterdayBut);
        tomm = (Button) findViewById(R.id.tomorrowBut);
        update = (Button) findViewById(R.id.update);
        final Calendar cal = Calendar.getInstance();
        
        final int day = cal.get(Calendar.DAY_OF_WEEK);
        final int source = (extras.getString("name").equalsIgnoreCase("Gator Corner Dining Center")) ? 1 : 0; //set these (1 is gc and 0 is ffc)
        
        database = DatabaseHelper.getWritableDB();

    	if (!updateMenuLocal(day, source)) {
    		Log.v("Tommy", "DiningDisplay menu not found in local. Get online.");
    		updateMenu(day, source);
    	}
    	
    	update.setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
    			menu.setText("Loading . . .");
    			final int day_num;
    			if (menuTitle.getText() == "Tomorrow's Menu")
    				day_num = (day == Calendar.SATURDAY) ? Calendar.SUNDAY : (int)day + 1;
    			else if (menuTitle.getText() == "Yesterday's Menu")
    				day_num = (day == Calendar.SUNDAY) ? Calendar.SATURDAY : (int) day - 1;
    			else
    				day_num = day;
				updateMenu(day_num, source);
			}
    	});

    	yest.setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
    			if (menuTitle.getText() == "Tomorrow's Menu") {
    				yest.setText("Yesterday");
					menuTitle.setText("Today's Menu");
					tomm.setVisibility(View.VISIBLE);
					updateMenuLocal(day, source);
				} else if (day == Calendar.WEDNESDAY) {
	    			menu.setText("The menu for yesterday is not currently available.");
	    			try {
	    				wait(1500);
	    			} catch (InterruptedException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
	    			updateMenuLocal(day, source);
	    		} else {
	    			yest.setVisibility(View.GONE);
	    			menuTitle.setText("Yesterday's Menu");
	    			tomm.setText(" Today ");
	    			final int yes = (day == Calendar.SUNDAY) ? Calendar.SATURDAY : (int) day - 1;
	    			if (!updateMenuLocal(yes, source)) {
	    				Log.v("Tommy", "DiningDisplay menu not found in local. Get online.");
	    				menu.setText("Loading . . .");
	    				updateMenu(yes, source);
	    			}
				}
	    	}
	    });

		tomm.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (menuTitle.getText() == "Yesterday's Menu") {
					tomm.setText("Tomorrow");
					menuTitle.setText("Today's Menu");
					yest.setVisibility(View.VISIBLE);
					updateMenuLocal(day, source);
				} else if (day == Calendar.TUESDAY) {
					menu.setText("The menu for tomorrow is not currently available.");
					try {
						wait(1500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					updateMenuLocal(day, source);
				} else {
					tomm.setVisibility(View.GONE);
	    			menuTitle.setText("Tomorrow's Menu");
	    			yest.setText(" Today ");
					final int tom = (day == Calendar.SATURDAY) ? 1 : (int)day + 1;
					if (!updateMenuLocal(tom, source)) {
			    		Log.v("Tommy", "DiningDisplay menu not found in local. Get online.");
			    		menu.setText("Loading . . .");
			    		updateMenu(tom, source);
			    	}
				}
			}
		});
		
    }
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	private boolean updateMenuLocal(final int day_num, final int source) {	//on success return true. if DB not found, return false
		ArrayList<String> ret = new ArrayList<String>();
		Cursor menucursor = database.query("dining_menus", new String[] {"menu_item"}, "dining_id = " + source + " AND day_of_week = " + day_num, null, null, null, null);
		if (menucursor == null)
			System.err.println("TOMMY DEBUG: menucursor = null.");	//never prints
		menucursor.moveToFirst();
		if (menucursor.getCount() > 0) {	//table not empty?
	        while (menucursor.isAfterLast() == false) {
	        	ret.add(menucursor.getString(0));
	            menucursor.moveToNext();
	        }
			String list[] = ret.toArray(new String[0]);
			menu.setText("");
			
			for (int i = 0; i < list.length; i++) {
				menu.append(list[i] + "\n");
			}
			return true;
		} else {
			return false;
		}
	}
	
	private void updateMenu(final int day_num, final int source) {
		final String day;
		switch (day_num) {
		case Calendar.SUNDAY:
			day = "Sunday";
			break;
		case Calendar.MONDAY:
			day = "Monday";
			break;
		case Calendar.TUESDAY:
			day = "Tuesday";
			break;
		case Calendar.WEDNESDAY:
			day = "Wednesday";
			break;
		case Calendar.THURSDAY:
			day = "Thursday";
			break;
		case Calendar.FRIDAY:
			day = "Friday";
			break;
		default:
			day = "Saturday";
			break;
		}
		String[] url = new String[] {"ffc.json","gc.json"};
        myHttpClient.get(url[source], null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String json) {
            	menu.setText("");
        		JSONTokener tokener = new JSONTokener(json);
        		JSONObject finalResult = null;
				try {
					finalResult = new JSONObject(tokener);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        		JSONArray jsonObject = null;
				try {
					jsonObject = finalResult.getJSONArray(day);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				//delete entries for this dining hall and day of week from table
				database.delete("dining_menus", "dining_id = " + source + " AND day_of_week = " + day_num, null);
				
                for (int i = 0; i < jsonObject.length(); i++) {
        				try {
        					String add = jsonObject.getJSONArray(i).getString(0);
        					ContentValues cValues = new ContentValues();
        					
        					cValues.put("dining_id", source);
        					cValues.put("day_of_week", day_num);
        					cValues.put("menu_item", add);
        					
							if (database.insertOrThrow("dining_menus", null, cValues) == -1)
								System.err.println("TOMMY DEBUG: Database insert failed.");
							
							menu.append(add + "\n");
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SQLException se) {
							se.printStackTrace();
						}
                }
            }
        });
	}
	
}
